import axios from "axios";
import { getToken, removeToken, setToken } from '@/utils/token.js';
import errorcode from "./errorcode.js";

import { ElNotification, ElMessageBox, ElMessage } from "element-plus";

// 创建实例时配置默认值
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000, // 超时时间
});
export let isRelogin = { show: false };
// 添加请求拦截器
request.interceptors.request.use(
  function (config) {
         const isToken = (config.headers || {}).isToken === false;
    // 在发送请求之前做些什么
    if (getToken() && !isToken) {
      config.headers["Authorization"] = "Bearer " + getToken();
    }
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
request.interceptors.response.use(
  function (response) {
    const code = response.data.code || 200;
    const msg = errorcode[code] || response.data.msg || "未知错误";
    if (code == 401) {
      if (!isRelogin.show) {
        isRelogin.show = true;
        ElMessageBox.confirm(
          "登录状态已过期，您可以继续留在该页面，或者重新登录",
          "系统提示",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            isRelogin.show = false;
          })
          .catch(() => {
            isRelogin.show = false;
            removeToken();
            location.href = "/login";
          });
      }
       return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
    } else if (code == 500) {
          ElMessage({ message: msg, type: "error" });
          return Promise.reject(new Error(msg));
    } else if (code == 601) {
          ElMessage({ message: msg, type: "error" });
          return Promise.reject(new Error(msg));
    } else if (code != 200) {
          ElMessage({ message: msg, type: "error" });
          return Promise.reject(new Error(msg));
    } else {
      return Promise.resolve(response.data);
    }

  },
  function (error) {
    let { message } = error.message;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    }
      ElMessage({ message: message, type: "error", duration: 5 * 1000 });
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);
export default request;